package net.xju3_4.service.impl;

import net.xju3_4.dao.UserProfileDao;
import net.xju3_4.entity.UserEntity;
import net.xju3_4.service.UserProfileService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户资料服务实现类
 */
public class UserProfileServiceImpl implements UserProfileService {
    
    private UserProfileDao userProfileDao = new UserProfileDao();
    
    @Override
    public UserEntity getUserProfile(String userId) {
        try {
            return userProfileDao.selectUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public boolean updateUserProfile(Map<String, Object> updateData) {
        try {
            String userId = (String) updateData.get("userId");
            String realName = (String) updateData.get("realName");
            String phone = (String) updateData.get("phone");
            String avatarUrl = (String) updateData.get("avatarUrl");
            String idCard = (String) updateData.get("idCard");
            String driverLicense = (String) updateData.get("driverLicense");

            System.out.println("DEBUG: 更新用户资料 - userId: " + userId);
            System.out.println("DEBUG: realName: " + realName);
            System.out.println("DEBUG: phone: " + phone);
            System.out.println("DEBUG: avatarUrl: " + avatarUrl);
            System.out.println("DEBUG: idCard: " + idCard);
            System.out.println("DEBUG: driverLicense: " + driverLicense);

            // 检查手机号是否已被其他用户使用
            if (phone != null && !phone.trim().isEmpty() && isPhoneExists(phone, userId)) {
                System.out.println("DEBUG: 手机号已存在: " + phone);
                return false;
            }

            return userProfileDao.updateUserProfile(userId, realName, phone, avatarUrl, idCard, driverLicense);

        } catch (Exception e) {
            System.out.println("DEBUG: 更新用户资料异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean changePassword(String userId, String oldPassword, String newPassword) {
        try {
            // 验证原密码
            if (!verifyIdentity(userId, oldPassword)) {
                return false;
            }
            
            // 更新密码（这里应该加密存储）
            return userProfileDao.updatePassword(userId, newPassword);
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean updateAvatar(String userId, String avatarUrl) {
        try {
            return userProfileDao.updateAvatar(userId, avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public Map<String, Object> checkProfileCompleteness(String userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            UserEntity user = getUserProfile(userId);
            if (user == null) {
                result.put("completeness", 0);
                result.put("message", "用户不存在");
                return result;
            }
            
            int totalFields = 6; // 总字段数
            int completedFields = 0;
            List<String> missingFields = new ArrayList<>();
            
            // 检查各个字段
            if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("用户名");
            }
            
            if (user.getRealName() != null && !user.getRealName().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("真实姓名");
            }
            
            if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("手机号");
            }
            
            if (user.getAvatarUrl() != null && !user.getAvatarUrl().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("头像");
            }
            
            if (user.getIdCardEncrypted() != null && !user.getIdCardEncrypted().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("身份证号");
            }
            
            if (user.getDriverLicenseEncrypted() != null && !user.getDriverLicenseEncrypted().trim().isEmpty()) {
                completedFields++;
            } else {
                missingFields.add("驾驶证号");
            }
            
            // 计算完整性百分比
            int completeness = (int) ((double) completedFields / totalFields * 100);
            
            result.put("completeness", completeness);
            result.put("completedFields", completedFields);
            result.put("totalFields", totalFields);
            result.put("missingFields", missingFields);
            
            // 生成建议
            if (completeness < 100) {
                result.put("suggestions", getProfileSuggestions(userId));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("completeness", 0);
            result.put("message", "检查失败");
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> getSecurityInfo(String userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            UserEntity user = getUserProfile(userId);
            if (user == null) {
                result.put("error", "用户不存在");
                return result;
            }
            
            // 安全信息（脱敏处理）
            result.put("username", user.getUsername());
            result.put("phone", maskPhone(user.getPhone()));
            result.put("hasIdCard", user.getIdCardEncrypted() != null && !user.getIdCardEncrypted().trim().isEmpty());
            result.put("hasDriverLicense", user.getDriverLicenseEncrypted() != null && !user.getDriverLicenseEncrypted().trim().isEmpty());
            result.put("accountStatus", user.getStatus() == 1 ? "正常" : "禁用");
            
            // 安全等级评估
            int securityLevel = calculateSecurityLevel(user);
            result.put("securityLevel", securityLevel);
            result.put("securityLevelText", getSecurityLevelText(securityLevel));
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("error", "获取安全信息失败");
        }
        
        return result;
    }
    
    @Override
    public boolean verifyIdentity(String userId, String password) {
        try {
            UserEntity user = getUserProfile(userId);
            if (user == null) {
                return false;
            }
            
            // 这里应该使用加密后的密码进行比较
            return password.equals(user.getPassword());
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean isPhoneExists(String phone, String excludeUserId) {
        try {
            return userProfileDao.checkPhoneExists(phone, excludeUserId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getProfileSuggestions(String userId) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> suggestions = new ArrayList<>();
        
        try {
            UserEntity user = getUserProfile(userId);
            if (user == null) {
                return result;
            }
            
            // 生成具体建议
            if (user.getRealName() == null || user.getRealName().trim().isEmpty()) {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("field", "realName");
                suggestion.put("title", "完善真实姓名");
                suggestion.put("description", "填写真实姓名有助于提高账户安全性");
                suggestion.put("priority", "high");
                suggestions.add(suggestion);
            }
            
            if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("field", "phone");
                suggestion.put("title", "绑定手机号");
                suggestion.put("description", "绑定手机号可用于账户找回和安全验证");
                suggestion.put("priority", "high");
                suggestions.add(suggestion);
            }
            
            if (user.getAvatarUrl() == null || user.getAvatarUrl().trim().isEmpty()) {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("field", "avatar");
                suggestion.put("title", "上传头像");
                suggestion.put("description", "上传头像让您的账户更加个性化");
                suggestion.put("priority", "medium");
                suggestions.add(suggestion);
            }
            
            if (user.getIdCardEncrypted() == null || user.getIdCardEncrypted().trim().isEmpty()) {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("field", "idCard");
                suggestion.put("title", "实名认证");
                suggestion.put("description", "完成实名认证可享受更多服务");
                suggestion.put("priority", "medium");
                suggestions.add(suggestion);
            }
            
            if (user.getDriverLicenseEncrypted() == null || user.getDriverLicenseEncrypted().trim().isEmpty()) {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("field", "driverLicense");
                suggestion.put("title", "驾驶证认证");
                suggestion.put("description", "上传驾驶证信息以便租车服务");
                suggestion.put("priority", "high");
                suggestions.add(suggestion);
            }
            
            result.put("suggestions", suggestions);
            result.put("count", suggestions.size());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 手机号脱敏处理
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.length() < 7) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
    }
    
    /**
     * 计算安全等级
     */
    private int calculateSecurityLevel(UserEntity user) {
        int level = 0;
        
        if (user.getPassword() != null && user.getPassword().length() >= 8) {
            level += 20;
        }
        
        if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
            level += 20;
        }
        
        if (user.getRealName() != null && !user.getRealName().trim().isEmpty()) {
            level += 20;
        }
        
        if (user.getIdCardEncrypted() != null && !user.getIdCardEncrypted().trim().isEmpty()) {
            level += 20;
        }
        
        if (user.getDriverLicenseEncrypted() != null && !user.getDriverLicenseEncrypted().trim().isEmpty()) {
            level += 20;
        }
        
        return level;
    }
    
    /**
     * 获取安全等级文本
     */
    private String getSecurityLevelText(int level) {
        if (level >= 80) {
            return "高";
        } else if (level >= 60) {
            return "中";
        } else {
            return "低";
        }
    }
}
